
import { Node } from './Node'

export class LinkedStack<T> implements Iterable<T> {

    private first: Node<T> | null;     // 栈顶元素，也是最近添加的元素
    private N: number = 0;      // 数量

    constructor () {
        this.first = null;
        this.N = 0;
    }

    public isEmpty () {
        return this.N === 0;
    }

    public size () {
        return this.N;
    }

    public push (item: T) {
        const oldFirst = this.first;
        this.first = new Node();
        this.first.item = item;
        this.first.next = oldFirst;
        this.N++;
    }

    public pop () {
        if (this.first) {
            const item = this.first.item;
            this.first = this.first.next;
            this.N--;
            return item;
        } else {
            return undefined;
        }
    }

    [Symbol.iterator](): Iterator<T, any, undefined> {
        let curNode = this.first;
        return {
            next: () => {
                if (curNode) {
                    const node = curNode;
                    curNode = curNode.next;
                    return { done: false, value: node.item as T }
                } else {
                    return { done: true, value: null }
                }
            },
            return: () => {
                return { done: true, value: null }
            }
        }
    }

}